package game.phases.actionphase.commands 
{
	import core.Command;
	import game.mapviewer.popups.battle.BattlePopup;
	import game.unitmanager.ArmyController;
	/**
	 * ...
	 * @author Sulus Ltd.
	 */
	public class GetSupportCommand extends Command
	{
		private var supportingArmies:Array;
		private var sideA:Array;
		private var sideB:Array;
		private var bPopup:BattlePopup;
		private var currentIdx:int = -1;
		
		public function GetSupportCommand(supportingArmies:Array, sideA:Array, sideB:Array, bPopup:BattlePopup) 
		{
			this.supportingArmies = supportingArmies.slice();
			this.sideA = sideA;
			this.sideB = sideB;
			this.bPopup = bPopup;
		}
		
		override public function Execute():void 
		{
			super.Execute();
			
			//sort by initiative
			supportingArmies.sort(
				function(armyA:ArmyController, armyB:ArmyController):Number
				{
					var priceA:Number = armyA.GetInitiative();
					var priceB:Number = armyB.GetInitiative();
					
					if (priceA > priceB) return 1;
					if (priceA < priceB) return -1;
					return 0;
				}
			);
			
			
			
			AskNextArmy();
		}
		
		private function OnSupportAnswer(supportWho:int):void
		{
			switch (supportWho) 
			{
				case 0: // attacker
				{
					sideA.push(supportingArmies[currentIdx]);
				}	
				break;
				case 1: // defender
				{
					sideB.push(supportingArmies[currentIdx]);
				}	
				break;
				case 2: // noone
				{
					
				}	
				break;
			}
			
			AskNextArmy();
		}
		
		private function AskNextArmy():void
		{
			//show panel
			currentIdx++;
			
			if (currentIdx<supportingArmies.length)
				bPopup.AskSupport(supportingArmies[currentIdx], OnSupportAnswer);
			else
			{
				Callback();
			}
		}
		
	}

}